package com.mine.interview;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class ExchangePrint {
    private Thread thread1;
    private Thread thread2;

    /**
     * @throws InterruptedException
     */
    @Test
    public void lockSupport() throws InterruptedException {
        List<Integer> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        get26English(list1, list2);
        thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (Integer integer : list1) {
                    System.out.println(integer);
                    LockSupport.unpark(thread2);
                    LockSupport.park(this);
                }
            }
        });
        thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (String string : list2) {
                    LockSupport.park(this);
                    System.out.println(string);
                    LockSupport.unpark(thread1);
                }
            }
        });
        thread1.start();
        thread2.start();
        Thread.sleep(10000000);
    }

    public static void get26English(List<Integer> numList, List<String> english) {
        for (int i = 1; i < 27; i++) {
            numList.add(i);
        }
        for (int i = 0; i < 26; i++) {
            char c = (char) ('A' + i);
            english.add(String.valueOf(c));
        }
    }

    @Test
    public void waitNotify() throws InterruptedException {
        List<Integer> list1 = new ArrayList<>();
        List<String> list2 = new ArrayList<>();
        get26English(list1, list2);
        Object o = new Object();
        thread1 = new Thread(() -> {
            synchronized (o) {
                for (Integer integer : list1) {
                    System.out.println(integer);
                    o.notify();
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                o.notify();
            }
        });
        thread2 = new Thread(() -> {
            synchronized (o) {
                for (String string : list2) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(string);
                    o.notify();
                }
                o.notify();
            }
        });
        thread2.start();
        thread1.start();

        TimeUnit.SECONDS.sleep(10);
    }
}
